window.onload = function() {
    init();

    var circleArr;

    var curCat = {x: 4, y: 4};

    function clicked(e) {
        if (e.target._circleType == 3) return;
        e.target.setCircleType(2);

        var dir = [[-1, 0], [1, 1], [-1, 1], [1, 0], [-1, -1], [1, -1]];
        for (i in dir) {
            var td = dir[i];
            var newPosi = [Number(curCat.x) + td[0], Number(curCat.y) + td[1]];
            console.log(td);
            if (newPosi[0] < 9 && newPosi[0] >= 0 && newPosi[1] < 9 && newPosi[1] >= 0 && circleArr[newPosi[0]][newPosi[1]]._circleType == 1) {
                circleArr[curCat.x][curCat.y].setCircleType(1);
                curCat.x = newPosi[0];
                curCat.y = newPosi[1];
                circleArr[curCat.x][curCat.y].setCircleType(3);
                break;
            }
        }
        if (curCat.x == 0 || curCat.x == 8 || curCat.y == 0 || curCat.y == 8) {
            alert('游戏结束!')
            reStart();
        }
    }

    function addCircle(gameView) {
        for (var i = 0; i < 9; i++) {
            for (var j = 0; j < 9; j++) {
                var c = new Circle();
                gameView.addChild(c);
                circleArr[i][j] = c;
                c.x = i * 12 + (j % 2 ? 6 : 0);
                c.y = j * 12;
                //给每个圆添加点击事件
                c.addEventListener('click', clicked);
            }
        }
        
    }
    

    

    function reStart() {
        reSet();
        //设置猫的位置
        circleArr[4][4].setCircleType(3);
    }

    function reSet() {
        for (i in circleArr) {
            var cir = circleArr[i];
            for (j in cir) {
                circleArr[i][j].setCircleType(1);
            }
        }
        curCat = {x: 4, y: 4};
    }
    
    function init() {
        var stage = new createjs.Stage('gameView');
        createjs.Ticker.framerate = 30;
        createjs.Ticker.addEventListener('tick', stage);

        var gameView = new createjs.Container();
        gameView.x = 30;
        gameView.y = 30;

        stage.addChild(gameView);
        console.log(11);
        circleArr = [];
        for (var i = 0; i < 9; i++) {
            circleArr.push([]);
        }
        addCircle(gameView);

        //设置猫的位置
        circleArr[4][4].setCircleType(3);
        
    }
}

